#class Pcap
#author jch
#date 2009-06-23
from xml.dom import minidom
import signal
import libvirt
import os
import sys
import commands

class Pcap:
    def __init__(self,vmiUUID,capature_nics,capature_expr=""):
         self.vmiUUID = vmiUUID;
         self.nics = capature_nics;
         self.expr = capature_expr;
         self.devs = [] 
    def stop(self):
         try:
            for nic in self.nics:
                file = open("/var/lib/ivic/vmc/images/"+self.vmiUUID+"/pcap"+str(nic)+".pid","r")
                pid = file.readline();
                ret = commands.getstatusoutput("ps aux | grep \""+pid+"\"")[1];
                ids = ret.split(" ");
                #print ids;
                p = ids[1];
                for i in range(len(ids)):
                    if i==0:
                        continue;
                    p = ids[i];
                    if (p!=""):
                        break;
                #print p;
                os.system("kill -9 "+p)
                os.system("echo hh>>/root/t.tt")
            return 0;
         except Exception,e:
            raise Exception,"failed to stop pcap:"+str(e);
            return -1;

    def start(self):
         self.devs = [];
         conn = libvirt.open(None)
         if conn == None:
             raise Exception,'Failed to open connection to the hypervisor';
             return -1;

         try:
             dom = conn.lookupByUUIDString(self.vmiUUID);
             domxml = dom.XMLDesc(1);
             if domxml=="":
                 raise Exception,"failed to get xmldesc from domain"
                 conn.close()
                 return -2;
             try:
                 xmldoc = minidom.parseString(domxml);
                 interfaces = xmldoc.getElementsByTagName("interface")
                 for i in range(len(interfaces)):
                     #network = interfaces[i].getElementsByTagName("source")[0].attributes["network"].value;
                     dev = interfaces[i].getElementsByTagName("target")[0].attributes["dev"].value;
                     self.devs.append(dev);

             except Exception,ex:
                 raise Exception,"failed pasre dom xml: "+str(ex);
                 conn.close()
                 return -3;
             
             for nic in self.nics:
                 scriptName = "/usr/sbin/tcpdump";
                 scriptargs = " -i "+self.devs[int(nic)]+" -C 50 -s 0 -w /var/lib/ivic/vmc/images/"+self.vmiUUID+"/pcap"+str(nic)+".log "+self.expr+" "
                 if not os.path.exists("/var/lib/ivic/vmc/images/"+self.vmiUUID):
                     os.system("mkdir -p /var/lib/ivic/vmc/images/"+self.vmiUUID)
                 os.system(scriptName+scriptargs+" &")
                 os.system("echo "+scriptName+" -i "+self.devs[int(nic)]+" > /var/lib/ivic/vmc/images/"+self.vmiUUID+"/pcap"+str(nic)+".pid &")
                 
             conn.close()
             return 0;
         except libvirt.libvirtError:
             raise Exception,"vmi %s not exists"%(vmiUUID)
             conn.close()
             return -2;
         except Exception,e:
             raise Exception,"ssss"+str(e)+self.expr+str(self.nics);
             conn.close()
             return -3;
if __name__=="__main__":
         try:
             pcap = Pcap("a691ea00-6bc8-11de-a5db-00188b2049d7",[0,]);
             pcap.start();
             #logger.info("stop pcap vm ok");
         except Exception,e:
             print "asf"+str(e);             
